package com.atldy.commerce.service;

import com.alibaba.fastjson.JSON;
import com.atldy.commerce.enums.CommonConstant;
import com.atldy.commerce.vo.JwtToken;
import com.atldy.commerce.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @version 1.0
 * @Author: li-dong-yang
 * @CreateTime: 2021-08-24 6:09
 * @Description：
 */
@Service
@Slf4j
public class UserRestTemplateService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    public JwtToken getToken(UsernameAndPassword usernameAndPassword) {
        String httpUrl = "http://localhost:7000/ecommerce-authority-center/authority/token";
        log.info("httpurl info [{}] rquestparameter infopath【{}】", httpUrl,
                JSON.toJSONString(usernameAndPassword));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        return new RestTemplate().postForObject(
                httpUrl, new HttpEntity<>(JSON.toJSON(usernameAndPassword), headers),
                JwtToken.class
        );

    }

    public JwtToken getTokenLoadBalancerC(UsernameAndPassword usernameAndPassword) {

        ServiceInstance serviceInstance = loadBalancerClient.choose(CommonConstant.AUTHORITY_CENTER_SERVICE_ID);
        log.info("注册中心服务是:[{}]", JSON.toJSONString(serviceInstance));

        String httpUrl = String.format(
                "http://%s:%s/ecommerce-authority-center/authority/token",
                serviceInstance.getHost(), serviceInstance.getPort()
        );
        log.info("httpurl info [{}] rquestparameter infopath【{}】", httpUrl,
                JSON.toJSONString(usernameAndPassword));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        return new RestTemplate().postForObject(
                httpUrl, new HttpEntity<>(JSON.toJSON(usernameAndPassword), headers),
                JwtToken.class
        );

    }


}